<?php

namespace app\common\service\driver;

use think\Exception;

/**
 * 本地存储驱动
 */
class LocalDriver
{
    protected $config;

    public function __construct($config)
    {
        $this->config = $config;
    }

    /**
     * 上传文件
     */
    public function upload($file, $fileInfo)
    {
        $configData = $this->config->config;
        $uploadPath = $configData['path'] ?? '/uploads';
        $uploadUrl = $configData['url'] ?? '/uploads';
        
        // 确保上传目录存在
        $fullPath = ROOT_PATH . 'public' . $uploadPath . '/' . $fileInfo['file_path'];
        $dir = dirname($fullPath);
        
        if (!is_dir($dir)) {
            if (!mkdir($dir, 0755, true)) {
                throw new Exception('无法创建目录：' . $dir);
            }
        }
        
        // 直接复制文件到目标位置，避免使用move()方法
        $sourcePath = $file->getRealPath();
        $targetPath = $dir . '/' . $fileInfo['file_name'];
        
        if (!$sourcePath || !file_exists($sourcePath)) {
            throw new Exception('源文件不存在');
        }
        
        if (!copy($sourcePath, $targetPath)) {
            throw new Exception('文件复制失败');
        }
        
        // 删除临时文件
        @unlink($sourcePath);
        
        // 生成访问URL
        $fileUrl = $uploadUrl . '/' . $fileInfo['file_path'];
        
        return [
            'file_path' => $fileInfo['file_path'],
            'file_url' => $fileUrl
        ];
    }

    /**
     * 删除文件
     */
    public function delete($filePath)
    {
        $configData = $this->config->config;
        $uploadPath = $configData['path'] ?? '/uploads';
        
        $fullPath = ROOT_PATH . 'public' . $uploadPath . '/' . $filePath;
        
        if (file_exists($fullPath)) {
            return unlink($fullPath);
        }
        
        return true;
    }

    /**
     * 获取文件URL
     */
    public function getUrl($filePath)
    {
        $configData = $this->config->config;
        $uploadUrl = $configData['url'] ?? '/uploads';
        
        return $uploadUrl . '/' . $filePath;
    }

    /**
     * 检查文件是否存在
     */
    public function exists($filePath)
    {
        $configData = $this->config->config;
        $uploadPath = $configData['path'] ?? '/uploads';
        
        $fullPath = ROOT_PATH . 'public' . $uploadPath . '/' . $filePath;
        
        return file_exists($fullPath);
    }
}
